package com.ruoyi.project.wenyanwen.export.service.impl;

import com.ruoyi.common.constant.DbGenerateResult;
import com.ruoyi.common.constant.DbGenerateStatus;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.sqlite.Jdbc;
import com.ruoyi.common.utils.sqlite.JdbcFactory;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.wenyanwen.export.domain.SqliteExport;
import com.ruoyi.project.wenyanwen.export.mapper.SqliteExportMapper;
import com.ruoyi.project.wenyanwen.export.service.ISqliteExportService;
import com.ruoyi.project.wenyanwen.export.service.QueryService;
import com.ruoyi.project.wenyanwen.generate.domain.GenerateTask;
import com.ruoyi.project.wenyanwen.generate.service.IDbGenerateService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 数据表配置Service业务层处理
 *
 * @author shixiangwen
 * @date 2020-09-27
 */
@Service
@DataSource(DataSourceType.KKWENYANWEN)
public class SqliteExportServiceImpl implements ISqliteExportService {

    protected static Log logger = LogFactory.getLog(SqliteExportServiceImpl.class);

    @Autowired
    SqliteExportMapper sqliteExportMapper;

    @Autowired
    IDbGenerateService dbGenerateService;

    @Autowired
    QueryService queryService;

    /**
     * 查询数据表配置
     *
     * @param id 数据表配置ID
     * @return 数据表配置
     */
    @Override
    public SqliteExport selectSqliteExportById(Long id) {
        return sqliteExportMapper.selectSqliteExportById(id);
    }

    /**
     * 查询数据表配置列表
     *
     * @param sqliteExport 数据表配置
     * @return 数据表配置
     */
    @Override
    public List<SqliteExport> selectSqliteExportList(SqliteExport sqliteExport) {
        return sqliteExportMapper.selectSqliteExportList(sqliteExport);
    }

    /**
     * 新增数据表配置
     *
     * @param sqliteExport 数据表配置
     * @return 结果
     */
    @Override
    public int insertSqliteExport(SqliteExport sqliteExport) {
        return sqliteExportMapper.insertSqliteExport(sqliteExport);
    }

    /**
     * 修改数据表配置
     *
     * @param sqliteExport 数据表配置
     * @return 结果
     */
    @Override
    public int updateSqliteExport(SqliteExport sqliteExport) {
        return sqliteExportMapper.updateSqliteExport(sqliteExport);
    }

    /**
     * 删除数据表配置对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSqliteExportByIds(String ids) {
        return sqliteExportMapper.deleteSqliteExportByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除数据表配置信息
     *
     * @param id 数据表配置ID
     * @return 结果
     */
    @Override
    public int deleteSqliteExportById(Long id) {
        return sqliteExportMapper.deleteSqliteExportById(id);
    }

    @Override
    public void export(GenerateTask task) throws Exception {

        SqliteExport query = new SqliteExport();
        query.setDbName(task.getDbGenerate().getDbName());
        List<SqliteExport> list = this.selectSqliteExportList(query);
        for (SqliteExport sqliteExport : list) {
            this.export(task, sqliteExport);
            if (!task.isSuccess()) {
                return;
            }
        }

        Class.forName("org.sqlite.JDBC");
        Jdbc jdbc = JdbcFactory.getJdbc(task.getDbPath());
        jdbc.execute("PRAGMA user_version = " + task.getVersion());
    }

    private void updateProgress(GenerateTask task) {
        task.getDbGenerate().setProgress((long) task.getProgress());
        this.dbGenerateService.updateDbGenerate(task.getDbGenerate());
    }

    private void export(GenerateTask task, SqliteExport sqliteExport) throws Exception {

        Class.forName("org.sqlite.JDBC");

        Jdbc jdbc = JdbcFactory.getJdbc(task.getDbPath());
        jdbc.setAutoCommit(false);

        jdbc.execute("DROP TABLE IF EXISTS " + sqliteExport.getOutputTable());
        jdbc.execute(sqliteExport.getCreateSql());

        int start = 0;
        int size = 500;

        int total = 0;

        Class<?> cls = Class.forName(sqliteExport.getInputClass());
        com.ruoyi.project.wenyanwen.generate.convert.Convert convert = null;
        if (!StringUtils.isEmpty(sqliteExport.getConvertClass())) {
            if (SpringUtils.containsBean(sqliteExport.getConvertClass())) {
                convert = SpringUtils.getBean(sqliteExport.getConvertClass());
            } else {
                convert = (com.ruoyi.project.wenyanwen.generate.convert.Convert) Class.forName(sqliteExport.getConvertClass()).newInstance();
            }
        }

        List<?> list = queryService.query(sqliteExport.getDatasource(), sqliteExport.getInputTable(), sqliteExport.getInputSql(), cls, start, size);

        while (list.size() > 0) {

            if (task.isStop()) {
                task.setResult(DbGenerateResult.STOP);
                task.setStatus(DbGenerateStatus.CANCEL);
                return;
            }

            start += size;

            total += list.size();
            logger.info("importing.table[" + sqliteExport.getOutputTable() + "], finish[" + total + "]");

            task.addFinish(list.size());
            this.updateProgress(task);

            if (convert != null) {
                List<?> result = convert.convert(list);
                if (!result.isEmpty()) {
                    jdbc.insert(sqliteExport.getOutputTable(), result);
                }
            } else {
                jdbc.insert(sqliteExport.getOutputTable(), list);
            }

            list = queryService.query(sqliteExport.getDatasource(), sqliteExport.getInputTable(), sqliteExport.getInputSql(), cls, start, size);

            if (!RuoYiConfig.isProd() && total > 1000) {
                break;
            }
        }

        jdbc.commit();
    }

    @Override
    public int getCount(String dbName) {

        int count = 0;
        SqliteExport query = new SqliteExport();
        query.setDbName(dbName);
        List<SqliteExport> list = this.selectSqliteExportList(query);
        for (SqliteExport sqliteExport : list) {
            if (!StringUtils.isEmpty(sqliteExport.getInputSql())) {
                continue;
            }
            int c = queryService.count(sqliteExport.getDatasource(), sqliteExport.getInputTable());
            count += c;
        }

        return count;
    }
}
